(function () {
    var $,
        amplify,
        _editor,
        onSaveBook = onUpdateBook = cancelButton_onClick = function () {},
        dummyImageUrl = NatExt.wp.theme_url + '/patch/images/dummy-book-cover.jpg',
        mediaUploadUrlTemplate = _.template(NatExt.wp.media_upload_url + '?post_id=<%= post_id %>&type=image&TB_iframe=true');

    function Editor(rootElem, jQuery, amp) {
        $ = jQuery;
        amplify = amp;
        _editor = this;

        this.editor                     = $('.editor', rootElem);
        this.mainForm                   = $('.editor-form', this.editor);
        this.featuredImageRoot          = $('.featured-image', this.mainForm);
        this.featuredImage              = $('img', this.featuredImageRoot);
        this.featuredImageStorage       = $('[name="featured_image_id"]', this.mainForm);
        this.setFeaturedImageButton     = $('.set-featured-image', this.mainForm);
        this.removeFeaturedImageButton  = $('.remove-featured-image', this.mainForm);
        this.cancelButton               = $('.cancel-button', this.mainForm);
        this.submitButton               = $('[type="submit"]', this.mainForm);
        this.post_title                 = $('[name="post_title"]', this.mainForm);
        this.post_content               = $('[name="post_content"]', this.mainForm);
        this.bookstore_link             = $('[name="bookstore_link"]', this.mainForm);
        this.excerpt_home               = $('[name="excerpt_home"]', this.mainForm);
        this.excerpt_book               = $('[name="excerpt_book"]', this.mainForm);
        this.excerpt_pages              = $('[name="excerpt_pages"]', this.mainForm);
        this.autoContent                = $('[name="bookstore_auto_content"]', this.mainForm);

        this.cancelButton.click(function () {
            cancelButton_onClick();
        });

        this.setFeaturedImageButton.click(this.setFeaturedImage);
        this.removeFeaturedImageButton.click(this.removeFeaturedImage);
        this.mainForm.submit(this.onEditorSubmit);

        // Subscriptions
        // ------------------------------

        amplify.subscribe('bookCoverChanged', this.__bookCoverChanged);
        amplify.subscribe('editorModeChanged', this.__modeChanged);
        amplify.subscribe('editorModeChanged', this.__bookCoverChanged);
    };

    Editor.prototype.hide = function () {
        this.editor.hide();
    }

    Editor.prototype.show = function () {
        this.editor.fadeIn(300);
    }

    Editor.prototype.on = function (event, callback) {
        switch (event) {
            case 'cancel':
                cancelButton_onClick = callback;
                break;
            case 'saveBook':
                onSaveBook = callback;
                break;
            case 'updateBook':
                onUpdateBook = callback;
                break;
            default:
                break;
        }
    }

    Editor.prototype.reset = function () {
        this.featuredImage.attr('src', dummyImageUrl);
        this.featuredImageStorage.val('');
        this.mainForm.trigger('reset');
    }

    Editor.prototype.loadData = function (post_id, callback) {
        // reset fields first
        this.reset();

        $.ajax({
            type    : 'POST',
            url     : NatExt.wp.ajax_url,
            data    : {
                'action'    : 'NatExtAjax_Bookshelf',
                'post_id'   : post_id
            },
            success : function (data) {
                var post = $.parseJSON(data);

                // force tinyMCE in visual mode
                if (! tinyMCE.activeEditor) {
                    $('#book-content-tmce').trigger('click');
                }

                _editor.featuredImage.attr('src', post.post_thumbnail_url);
                _editor.featuredImageStorage.val(post.post_thumbnail_id);
                _editor.setFeaturedImageButton.attr('href', mediaUploadUrlTemplate({post_id: post.post_id}));
                _editor.post_title.val(post.post_title);
                tinyMCE.activeEditor.setContent(post.post_content);
                _editor.bookstore_link.val(post.bookstore_link);
                _editor.excerpt_home.val(post.excerpt_home);
                _editor.excerpt_book.val(post.excerpt_book);
                _editor.excerpt_pages.val(post.excerpt_pages);

                amplify.publish('bookCoverChanged');
            },
            complete : callback
        });
    }

    Editor.prototype.setFeaturedImage = function (event) {
        event.preventDefault();

        var formfield   = _editor.featuredImageStorage,
            preview     = _editor.featuredImage;

        tb_show('Add Book Cover', $(this).attr('href'), false);

        window.send_to_editor = function(html) {
            var imgurl  = $('img', html).attr('src'),
                classes = $('img', html).attr('class'),
                id      = classes.replace(/(.*?)wp-image-/, '');

            formfield.val(id);
            preview.attr('src', imgurl);

            amplify.publish('bookCoverChanged');

            tb_remove();
        }
    }

    Editor.prototype.removeFeaturedImage = function (event) {
        event.preventDefault();

        // remove the image only if it is not empty
        // just for safety
        _editor.featuredImageStorage.val('');
        _editor.featuredImage.attr('src', dummyImageUrl);

        amplify.publish('bookCoverChanged');
    }

    Editor.prototype.isCoverEmpty = function () {
        var fileName = _.last(_editor.featuredImage.attr('src').split('/'));

        return (fileName === 'dummy-book-cover.jpg');
    }

    Editor.prototype.setMode = function (mode) {
        mode = mode || 'normal';

        this.editor.attr('data-mode', mode);

        amplify.publish('editorModeChanged', {mode: mode});
    }

    Editor.prototype.getMode = function () {
        return this.editor.attr('data-mode');
    }

    Editor.prototype.setPostId = function (id) {
        id = id || '';

        this.editor.attr('data-post-id', id);
    }

    Editor.prototype.getPostId = function () {
        return this.editor.attr('data-post-id');
    }

    Editor.prototype.onEditorSubmit = function (event) {
        event.preventDefault();

        var ajaxData = {
            'action'                : 'NatExtAjax_Bookshelf_AddBook',
            'featured_image_id'     : _editor.featuredImageStorage.val(),
            'post_title'            : _editor.post_title.val(),
            'post_content'          : tinyMCE.activeEditor.getContent(),
            'bookstore_link'        : _editor.bookstore_link.val(),
            'excerpt_home'          : _editor.excerpt_home.val(),
            'excerpt_book'          : _editor.excerpt_book.val(),
            'excerpt_pages'         : _editor.excerpt_pages.val(),
            'bookstore_auto_content': _editor.autoContent.is(':checked'),
            'post_id'               : _editor.getPostId()
        };

        $.ajax({
            type : 'POST',
            url  : NatExt.wp.ajax_url,
            data : ajaxData,
            success : function () {
                if (ajaxData.post_id) {
                    // this is new
                    onSaveBook();
                } else {
                    onUpdateBook(ajaxData.post_id);
                }
            }
        });
    }


    // Subscribers
    // ------------------------------

    Editor.prototype.__bookCoverChanged = function () {
        if (_editor.isCoverEmpty()) {
            _editor.setFeaturedImageButton.show();
            _editor.removeFeaturedImageButton.hide();
        } else {
            _editor.setFeaturedImageButton.hide();
            _editor.removeFeaturedImageButton.show();
        }
    }

    Editor.prototype.__modeChanged = function (data) {
        switch (data.mode) {
            case 'edit':
                _editor.submitButton.val('Update Book');
                break;
            case 'add':
                _editor.submitButton.val('Add Book');
                break;
            default:
                _editor.submitButton.val('Save Book');
                break;
        }
    }

    window.BookshelfEditor = Editor;
}());

